﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Media.Imaging;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows.Resources;
using Microsoft.Xna.Framework.Media;
using Microsoft.Phone.Tasks;

namespace MangaKurosagi
{
    public class ImageHelper
    {
        public static void saveImage(string fileName,string Url)
        {
            Exception error = new Exception();
            Uri uri = new Uri(Url, UriKind.Absolute);
            HttpWebRequest request = HttpWebRequest.Create(uri) as HttpWebRequest;
            request.BeginGetResponse((ar) =>
            {
                try
                {
                    var response = request.EndGetResponse(ar);
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        using (IsolatedStorageFile localFile = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            using (var stream = response.GetResponseStream())
                            {
                                if (localFile.FileExists(fileName))
                                {
                                    localFile.DeleteFile(fileName);
                                }
                                using (IsolatedStorageFileStream fs = localFile.CreateFile(fileName))
                                {
                                    stream.CopyTo(fs);
                                }
                            }
                        }
                    });
                }
                catch(Exception ex)
                {
                    error = ex;
                }
            }, null);
        }
        public static BitmapImage LoadImage(string FileName)
        {
            BitmapImage bi = new BitmapImage();

            using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(FileName, FileMode.Open, FileAccess.Read))
                {
                    bi.SetSource(fileStream);
                }
            }
            return bi;
        }
    }
}
